package org.example.uhy.supports.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class LocalDateTimeUtils {
    private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dateCompactFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");


    public static String format(LocalDateTime ldt) {
        return dateTimeFormatter.format(ldt);
    }

    public static String format(LocalDate ld) {
        return dateFormatter.format(ld);
    }

    public static String formatCompact(LocalDate ld) {
        return dateCompactFormatter.format(ld);
    }

    public static LocalDateTime parse(String s) {
        if (s == null) {
            return null;
        }
        try {
            if (s.length() > 10) {
                return LocalDateTime.parse(s, dateTimeFormatter);
            } else if (s.length() == 10) {
                LocalDate date = LocalDate.parse(s, dateFormatter);
                return date.atStartOfDay();
            } else if (s.length() == 8) {
                LocalDate date = LocalDate.parse(s, dateCompactFormatter);
                return date.atStartOfDay();
            } else {
                throw new RuntimeException("不支持该时间格式: " + s);
            }
        } catch (Throwable e) {
            throw new RuntimeException("非法的时间: " + s);
        }
    }

    public static LocalDate parseDate(String s) {
        if (s == null) {
            return null;
        }
        try {
            if (s.length() > 10) {
                return LocalDateTime.parse(s, dateTimeFormatter).toLocalDate();
            } else if (s.length() == 10) {
                return LocalDate.parse(s, dateFormatter);
            } else if (s.length() == 8) {
                return LocalDate.parse(s, dateCompactFormatter);
            } else {
                throw new RuntimeException("不支持该时间格式: " + s);
            }
        } catch (Throwable e) {
            throw new RuntimeException("非法的时间: " + s);
        }
    }

    public static LocalDateTime maxTimeOfDay(LocalDateTime ldt) {
        return ldt.withHour(23).withMinute(59).withSecond(59);
    }

    public static LocalDateTime minTimeOfDay(LocalDateTime ldt) {
        return ldt.withHour(0).withMinute(0).withSecond(0);
    }

    public static LocalDateTime wrap(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}